<?php
/**
 * 会员中心
 * ============================================================================
 * 网站地址: http://www.pcfcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小潘 <1131680521@qq.com>
 * Date: 2019-12-21
 */
namespace app\home\controller\user;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cookie;
use app\home\model\Users as usermodel;
use app\home\logic\SmtpmailLogic;

class Users extends Base
{
    public function initialize() 
	{
        parent::initialize();
        $usermodel = new usermodel();
        $userinfo = $usermodel->getinfo();
        $userinfo['litpic'] = get_default_pic($userinfo['litpic']);
        $this->assign('userinfo', $userinfo);
        // 获取当前页面URL
        $result['pageurl'] = 'index';
        $gzpcf = array('field' => $result);
        $this->gzpcf = array_merge($this->gzpcf, $gzpcf);
        $this->assign('gzpcf', $this->gzpcf);
    }

    // 用户登陆
    public function login()
    {
        $gzpcfglobal = get_global();
        if ($this->users_id > 0) {
            $this->redirect(url('/user.users/users_center')->suffix('html')->domain(true)->build());
        }
		$users_open_login = getUsersConfigData('users.users_open_login');
		if($users_open_login == 0 || empty($users_open_login)){
			abort(404,'用户登录已经关闭');
		}
        // 默认开启验证码
        $is_vertify = 1;
        $users_login_captcha = $gzpcfglobal['home_users_login'];
        if (empty($users_login_captcha['is_on']) && $users_login_captcha['is_on'] == 0) {
            $is_vertify = 0;
        }
        $this->assign('is_vertify', $is_vertify);
        if (Request::isPost()) {
            $post = input('post.');
            $post['phone'] = trim($post['phone']);
            if (empty($post['phone'])) {
                $result = ['code' => 0, 'msg' => '登陆手机不能为空！'];
                return $result;
            }
            if (empty($post['pwd'])) {
                $result = ['code' => 0, 'msg' => '密码不能为空！'];
                return $result;
            }
            if (1 == $is_vertify) {
                if (empty($post['vertify'])) {
                    $result = ['code' => 0, 'msg' => '验证码不能为空！'];
                    return $result;
                }
                if(!captcha_check($post['vertify'])){
                    $result = ['code' => 0, 'msg' => '验证码错误！'];
                    return $result;
                }
            }
            $users = Db::name("users")->where('mobile', $post['phone'])->find();
            if (!empty($users)) {

                if (!empty($users['is_del'])) {
                    $result = ['code' => 0, 'msg' => '该会员已被删除，请联系管理员！'];
                    return $result;
                }
                if (empty($users['status'])) {
                    $result = ['code' => 0, 'msg' => '该会员尚未激活，请联系管理员！'];
                    return $result;
                }
                $users_id = $users['id'];
                if (strval($users['password']) === strval(func_encrypt($post['pwd']))) {
                    // 判断是前台还是后台注册的会员，后台注册不受注册验证影响，1为后台注册，2为前台注册。
                    if (2 == $users['register_place']) {
                        $usersVerificationRow = Db::name('users_config')->where('name','users_verification')->find();
                        if ($usersVerificationRow['update_time'] <= $users['add_time']) {
                            // 判断是否需要后台审核
                            if ($usersVerificationRow['value'] == 1 && $users['status'] == 0) {
                                $result = ['code' => 0, 'msg' => '管理员审核中，请稍等！'];
                                return $result;
                            }
                        }
                    }
                    unset($users['password']);
                    // 会员users_id存入session
                    Session::set('pcfcms_users_id',$users_id);
					Cookie::forever('pcfcms_users_id', $users_id);
                    $RecordData = [ 'login_time' => time()];
                    Db::name("users")->where('id',$users_id)->update($RecordData);
                    $result = ['code' => 1, 'msg' => '登录成功','url' => url('/user.users/users_center')->suffix('html')->domain(true)->build()];
                    return $result;
                }else{
                    $result = ['code' => 0, 'msg' => '密码不正确！'];
                    return $result;
                }
            }else{
                $result = ['code' => 0, 'msg' => '该号码不存在，请注册！'];
                return $result;
            }
        }
        return $this->fetch(':user/users_login');
    }

    // 用户注册
    public function reg()
    {
        $gzpcfglobal = get_global();
        if ($this->users_id > 0) {
            $this->redirect(url('/user.users/users_center')->suffix('html')->domain(true)->build());
        }
		$users_reg_open = getUsersConfigData('users.users_open_reg');
		if($users_reg_open == 0 || empty($users_reg_open)){
			abort(404,'用户注册已经关闭');
		}
        // 默认开启验证码
        $is_vertify = 1;
        $users_login_captcha = $gzpcfglobal['home_users_reg'];
        if (empty($users_login_captcha['is_on']) && $users_login_captcha['is_on'] == 0) {
            $is_vertify = 0;
        }
        $this->assign('is_vertify', $is_vertify);
        if (Request::isPost()) {
            $users_verification = !empty(getUsersConfigData('users.users_verification')) ? getUsersConfigData('users.users_verification') : 0;
            $post = input('post.');
            $post['phone'] = trim($post['phone']);
            if (empty($post['phone'])) {
                $result = ['code' => 0, 'msg' => '手机号码不能为空！'];
                return $result;
            }
            if (empty($post['code'])) {
                $result = ['code' => 0, 'msg' => '验证码不能为空！'];
                return $result;
            }
            if (1 == $is_vertify) {
                if (empty($post['vertify'])) {
                    $result = ['code' => 0, 'msg' => '验证码不能为空！'];
                    return $result;
                }
                if(!captcha_check($post['vertify'])){
                    $result = ['code' => 0, 'msg' => '验证码错误！'];
                    return $result;
                }
            }
            if (empty($post['pwd'])) {
                $result = ['code' => 0, 'msg' => '密码不能为空！'];
                return $result;
            }
            //手机唯一性检测
            $user = new \app\common\model\Users();
            if ($user_info = $user->check_mobile($post['phone'])){
                $result = ['code' => 0, 'msg' => "手机{$post['phone']}已被注册"];
                return $result;
            }
			
            // 会员验证
            if (1 == $users_verification) {
                $data['status'] = 0; //等待后台激活
            }else if (2 == $users_verification){ 
                // 验证邮箱验证码
                $data['is_email'] = 1;
                $RecordWhere = [
                    'source'   => 2,
                    'email'    => $post['email'],
                    'status'   => 0,
                    'code'     => $post['email_code']
                ];
                $RecordData = [
                    'status'      => 1,
                    'update_time' => time(),
                ];
                $r = Db::name("smtp_log")->where($RecordWhere)->update($RecordData);
                if (!$r){
                    $result = ['code' => 0, 'msg' => "操作失败，邮箱验证码不正确"];
                    return $result;
                }else{
                    $RecordWhere1 = [
                        'source'   => 2,
                        'email'    => $post['email'],
                        'status'   => 1,
                        'code'     => $post['email_code']
                    ];
                    Db::name("smtp_log")->where($RecordWhere1)->delete();
                }
            }else if(3 == $users_verification){ 
                // 验证手机验证码
                $data['is_mobile'] = 1;
                $RecordWhere = [
                    'source'   => 2,
                    'mobile'    => $post['phone'],
                    'status'   => 0,
                    'code'     => $post['code']
                ];
                $RecordData = [
                    'status'      => 1,
                    'update_time' => time(),
                ];
                $r = Db::name("sms_log")->where($RecordWhere)->update($RecordData);
                if (!$r){
                    $result = ['code' => 0, 'msg' => "操作失败，手机验证码不正确"];
                    return $result;
                }else{
                    $RecordWhere1 = [
                        'source'   => 2,
                        'mobile'    => $post['phone'],
                        'status'   => 1,
                        'code'     => $post['code']
                    ];
                    Db::name("sms_log")->where($RecordWhere1)->delete();
                }
            }
            // 添加会员到会员表
		    $data['username']       = get_rand_str(10,0,0);
			$data['nickname']       = "会员";
            $data['jinbi']       = 100;
            $data['email']       = !empty($post['email']) ? $post['email'] : '';
            $data['mobile']       = !empty($post['phone']) ? $post['phone'] : '';
            $data['password']       = func_encrypt($post['pwd']);
            $data['litpic']       = '/common/images/user.png';
            $data['add_time']       = time();
            $data['login_time']    = time();
            $data['register_place'] = 2;  // 注册位置，后台注册不受注册验证影响，1为后台注册，2为前台注册。
            $users_id = Db::name("users")->insertGetId($data);
            // 判断会员是否添加成功
            if (!empty($users_id)) {
                if (1 == $users_verification){  // 需要后台审核
                    $result = ['code' => 1, 'msg' => "注册成功，等管理员激活才能登录！",'url'=>url('/user/login')->suffix(true)->domain(true)->build()];
                    return $result;
                }else{  // 无需审核，直接登陆
                    Session::set('pcfcms_users_id',$users_id);
                    if (Session::get('pcfcms_users_id')){
						Cookie::forever('pcfcms_users_id', $users_id);
                        $result = ['code' => 1, 'msg' => "注册成功，正在为您跳转至会员中心！",'url'=>url('/user.users/users_center')->suffix(true)->domain(true)->build()];
                        return $result;
                    }else{
                        $result = ['code' => 1, 'msg' => "注册成功，请登录！",'url'=>url('/user/login')->suffix(true)->domain(true)->build()];
                        return $result;
                    }
                }
            }
            $result = ['code' => 0, 'msg' => "注册失败"];
            return $result;
        }
        return $this->fetch(':user/users_reg');
    }

    // 退出登陆
    public function logout()
    {
        Session::set('pcfcms_users_id', null);
        Cookie::delete('pcfcms_users_id');
        $this->redirect(Request::domain());
    }

    // 会员中心
    public function users_center()
    {
        return $this->fetch(':user/users_center');
    }
    
    // 修改会员信息
    public function userinfo()
    {
        if (Request::isPost()) {
            $post = input('param.');
            $order['username'] = isset($post['username'])?$post['username']:'';
            $order['nickname'] = isset($post['nickname'])?$post['nickname']:'游客';
            $order['truename'] = isset($post['truename'])?$post['truename']:'游客';
            if(isset($post['email']) && !empty($post['email'])){
                $pattern="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
                if(!preg_match($pattern,$post['email'])){
                    $result = ['code' => 0, 'msg' => '邮箱格式错误！'];
                    return $result;  
                }
                $order['email'] = isset($post['email'])?$post['email']:'';    
            }else{
                $order['email'] = isset($post['email'])?$post['email']:'';
            }
            $order['qq'] = isset($post['qq'])?$post['qq']:'';
            $order['update_time'] = time();
            if(Db::name("users")->where('id',$this->users_id)->update($order)){
                $result = ['code' => 1, 'msg' => '修改成功'];
                return $result;    
            }else{
                $result = ['code' => 0, 'msg' => '修改失败'];
                return $result;                
            }
        }
        return $this->fetch(':user/userinfo');
    }

    // 修改会员密码
    public function safe()
    {
        if (Request::isPost()) {
            $post = input('param.');
            if(!isset($post['oldpwd']) || empty($post['oldpwd'])){
                $result = ['code' => 0, 'msg' => '请输入你的旧密码！'];
                return $result;
            }
            $users = Db::name("users")->where('id',$this->users_id)->find();
            if (strval($users['password']) != strval(func_encrypt($post['oldpwd']))) {
                $result = ['code' => 0, 'msg' => '旧密码不正确！'];
                return $result;
            }
            unset($users);
            if(!isset($post['userpwd']) || empty($post['userpwd'])){
                $result = ['code' => 0, 'msg' => '新密码不能为空！'];
                return $result;
            }
            if(!isset($post['userpwdok']) || empty($post['userpwdok'])){
                $result = ['code' => 0, 'msg' => '新密码不能为空！'];
                return $result;
            }else{
                if($post['userpwdok'] != $post['userpwd']){
                   $result = ['code' => 0, 'msg' => '二次输入密码不一样！'];
                   return $result;
                }
            }
            $data['password'] = isset($post['userpwd'])?$post['userpwd']:'';
            $data['update_time'] = time();
            if(Db::name("users")->where('id',$this->users_id)->update($data)){
                $result = ['code' => 1, 'msg' => '修改成功'];
                return $result;    
            }else{
                $result = ['code' => 0, 'msg' => '修改失败'];
                return $result;                
            }

        }
        return $this->fetch(':user/safe');
    }







}